/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.isd.listener;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 *
 * @author ctrosch
 *
 * Cuando el TimedOut sesión de usuario, ( {@ link # sessionDestroyed (HttpSessionEvent)} ) método será invocado.
 * Este método se hacen limpiezas necesario (cerrar la sesión del usuario, la actualización de registros de la BD y de auditoría, etc ..)
 * Como resultado, después de este método, vamos a estar en un estado claro y estable. Así que nada más que pensar
 * por sesión ha finalizado, el usuario puede hacer nada después de este punto.
 *
 *
 */

public class MySessionListener implements HttpSessionListener {


    /**
    * our apps security service bean responsible from doing necessary operations at
    * login/logout progress...
    */

    public MySessionListener() {

    }

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        //get the destroying session...
        HttpSession session = event.getSession();
        

    /*
    * nobody can reach user data after this point because session is invalidated already.
    * So, get the user data from session and save its logout information
    * before losing it.
    * User's redirection to the timeout page will be handled by the SessionTimeoutFilter.
    */
    try {
        prepareLogoutInfoAndLogoutActiveUser(session);
    }catch(Exception e) {
        
    }
  }

    /**
    * Gets the logged in user data from Acegi SecurityContext and makes necessary logout operations.
    */
    public void prepareLogoutInfoAndLogoutActiveUser(HttpSession httpSession) {

        //SecurityContext context = (SecurityContext) httpSession
        //.getAttribute(HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY);

        //if (context != null) {

        // get the authentication object from acegi context...
        //Authentication authentication = context.getAuthentication();

        // update user logoninfo from active session...
        //LogonInfo logonInfo = LogonInfoHolder.getLogonInfo();

        // set logout information...
        //logonInfo.setUserId(authentication.getName());
        //logonInfo.setLogonType(LogonInfo.LOGON_TYPE_LOGOUT);
        //logonInfo.setLogonTime(new Date());

        //if (logger.isDebugEnabled()) {
        //    logger.debug("Acegi SecuityContext found, calling logout service for user :" + logonInfo.getUserId());
       // }

        // logout (and save logout info in database)...
        //getSecurityService(httpSession.getServletContext()).logout();
        //} else {
        //    if (logger.isDebugEnabled()) {
         //       logger.warn("Acegi SecuityContext doesn't exist, no need to call logout service");
          //  }
       // }
    }

}